package edu.msg.jthr.web.servlets;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.msg.jthr.backend.exception.ServiceException;
import edu.msg.jthr.backend.model.Candidate;
import edu.msg.jthr.backend.model.Comment;
import edu.msg.jthr.backend.model.Job;
import edu.msg.jthr.backend.model.User;
import edu.msg.jthr.backend.service.CandidateService;
import edu.msg.jthr.backend.service.JobService;
import edu.msg.jthr.backend.service.UserService;
import edu.msg.jthr.web.util.RoleAssembler;

/**
 * @author Elod
 */
@WebServlet("/ShowCandidates")
public class ShowCandidates extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private CandidateService candidateService;
	@EJB
	private JobService jobService;
	@EJB
	private UserService userService;
	private static final int BUFFER_SIZE = 4096;
	private HttpSession session;
	private static final Logger LOG = LoggerFactory
			.getLogger(ShowCandidates.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ShowCandidates() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		User user = (User) session.getAttribute("activeUser");
		if (user == null) {
			user = userService.getUserByUserName(request.getUserPrincipal()
					.toString());
			String role = RoleAssembler.getRole(user.getUserGroups());
			session.setAttribute("role", role);
			session.setAttribute("activeUser", user);
		}
		List<Candidate> candidateList = Collections.emptyList();
		try {
			candidateList = candidateService.getAll();
		} catch (ServiceException e) {
			LOG.error(e.getMessage());
		}
		session.setAttribute("candidateList", candidateList);
		request.getRequestDispatcher("/pages/ShowCandidates.jsp").forward(
				request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		session = request.getSession(true);
		Candidate candidate = candidateService.getById(Long.parseLong(request
				.getParameter("candidateId")));
		if (request.getParameter("update") != null) {
			session.setAttribute("candidate", candidate);
			request.getRequestDispatcher("/pages/UpdateCandidate.jsp").forward(
					request, response);
		}
		if (request.getParameter("recommendToJob") != null) {
			List<Job> jobList = jobService.getJobsWhereNotApplied(candidate);
			session.setAttribute("candidate", candidate);
			session.setAttribute("jobList", jobList);
			request.getRequestDispatcher("/pages/RecommendToJob.jsp").forward(
					request, response);
		}
		if (request.getParameter("delete") != null) {
			try {
				candidateService.delete(candidate);
			} catch (ServiceException e) {
				LOG.error(e.getMessage(), e);
			}
			
			doGet(request, response);
		}
		if (request.getParameter("addInterview") != null) {
			session = request.getSession(true);
			List<User> userList = Collections.emptyList();
			try {
				userList = userService.getAll();
			} catch (ServiceException e) {
				LOG.error(e.getMessage(), e);
			}
			session.setAttribute("userList", userList);
			session.setAttribute("candidate", candidate);
			request.getRequestDispatcher("/pages/AddInterview.jsp").forward(
					request, response);
		}

		if (request.getParameter("addComment") != null) {
			session = request.getSession(true);
			String commentFromArea = request.getParameter("commentArea");

			Comment comment = new Comment();
			User user = (User) session.getAttribute("activeUser");
			comment.setUser(user);
			comment.setContent(commentFromArea);
			comment.setDate(Calendar.getInstance().getTime());
			candidate.getComments().add(comment);
			try {
				candidateService.update(candidate);
			} catch (ServiceException e) {
				LOG.error(e.getMessage(), e);
			}

			doGet(request, response);
		}

		/**
		 * CV downloading (PDF format)
		 */
		if (request.getParameter("download") != null) {
			try {

				InputStream inputStream = new ByteArrayInputStream(
						candidate.getCv());
				int fileLength = inputStream.available();
				String mimeType = "application/pdf";

				response.setContentType(mimeType);
				response.setContentLength(fileLength);
				String headerKey = "Content-Disposition";
				String headerValue = String.format("attachment");
				response.setHeader(headerKey, headerValue);

				OutputStream outStream = response.getOutputStream();

				byte[] buffer = new byte[BUFFER_SIZE];
				int bytesRead = -1;

				while ((bytesRead = inputStream.read(buffer)) != -1) {
					outStream.write(buffer, 0, bytesRead);
				}

				inputStream.close();
				outStream.close();

			} catch (IOException ex) {
				response.getWriter().print("IO Error: " + ex.getMessage());
			}
			doGet(request, response);
		}
	}
}
